import 'package:flutter/material.dart';
import 'package:flutterdemo/actualcombat/page/globalkeydemosub.dart';

class GlobalKeyDemo extends StatefulWidget {
  GlobalKeyDemo({Key key}) : super(key: key);

  @override
  _GlobalKeyDemoState createState() => _GlobalKeyDemoState();
}

class _GlobalKeyDemoState extends State<GlobalKeyDemo> {
  // 我们想要在外部改变该状态，这时候就需要使用 GlobalKey
  final GlobalKey<GlobalKeyDemoSubState> key =
      GlobalKey<GlobalKeyDemoSubState>();
  // ScaffoldState key 控制页面内的SnackBar显示
  final keys = GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: keys,
      appBar: AppBar(
        title: Text('GlobalKeyDemo'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.ac_unit),
            onPressed: () {
              keys.currentState.showSnackBar(
                SnackBar(
                  content: Text(
                    'copyinfo',
                  ),
                ),
              );
            },
          )
        ],
      ),
      body: ListView(
        children: <Widget>[
          Container(
            child: GlobalKeyDemoSub(
              key: key,
            ),
          ),
          Container(
            margin: EdgeInsets.all(2.0),
            child: Column(
              children: ['ValueKey', 'ObjectKey', 'UniqueKey '].map(
                (item) {
                  return Container(
                    // https://blog.csdn.net/weixin_43901866/article/details/88980514
                    // Key 派生出两种不同用途的 Key：LocalKey 和 GlobalKey。
                    // LocalKey
                    // Localkey 派生出了许多子类 key：
                    // ValueKey : ValueKey('String')
                    // ObjectKey : ObjectKey(Object)
                    // UniqueKey : UniqueKey()

                    // Valuekey 又派生出了 PageStorageKey : PageStorageKey('value')

                    key: Key(item),
                    // key: ValueKey(item),
                    // key: Key(item.toString()),
                    // key: UniqueKey(),
                    child: ListItem(item: item),
                  );
                },
              ).toList(),
            ),
          )
        ],
      ),
      floatingActionButton: FloatingActionButton(
        child: Text('开关'),
        onPressed: () {
          // 而从GlobalKey对象上，你可以得到几个有用的属性currentElement，currentWidget，currentState。+
          key.currentState.changeState();
        },
      ),
    );
  }
}

class ListItem extends StatefulWidget {
  final item;
  ListItem({Key key, this.item}) : super(key: key);

  @override
  _ListItemState createState() => _ListItemState();
}

class _ListItemState extends State<ListItem> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text(widget.item),
    );
  }
}
